package com.hit.basinfo.sort_algorithm;

/**
 * author:Charies Gavin
 * date:2019/1/8,10:39
 * https:github.com/guobinhit
 * description: 快速排序
 */
public class QuickSort {
    /**
     * 快速排序
     *
     * @param nums 待排序数组
     */
    public void quickSort(int[] nums) {
        if (nums == null || nums.length < 2) return;
        int left = 0, right = nums.length - 1;
        quickSort(nums, left, right);
    }

    /**
     * 快速排序
     *
     * @param nums  待排序数组
     * @param left  左侧索引，初始值为 0
     * @param right 右侧索引，初始值为 nums.length -1
     */
    private void quickSort(int[] nums, int left, int right) {
        if (nums == null || nums.length < 2) return;
        // 获取分割基准点
        int index = partition(nums, left, right);
        // 左侧排序
        if (left < index - 1) {
            quickSort(nums, left, index - 1);
        }
        // 右侧排序
        if (right > index) {
            quickSort(nums, index, right);
        }
    }

    /**
     * 获取分割基准点
     *
     * @param nums  待排序数组
     * @param left  左侧索引，初始值为 0
     * @param right 右侧索引，初始值为 nums.length -1
     * @return 分割基准点
     */
    private int partition(int[] nums, int left, int right) {
        // 默认为数组的中间元素
        int pivot = nums[(left + right) / 2];

        while (left <= right) {
            while (nums[left] < pivot) {
                left++;
            }
            while (nums[right] > pivot) {
                right--;
            }
            if (left <= right) {
                int temp = nums[right];
                nums[right] = nums[left];
                nums[left] = temp;
                left++;
                right--;
            }
        }
        return left;
    }
}
